package com.wits.qso.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authc.credential.PasswordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springside.modules.web.Servlets;

import com.wits.platform.common.constants.UserType;
import com.wits.platform.common.constants.ViewType;
import com.wits.platform.common.constants.WebConstants;
import com.wits.platform.common.utils.FileUtil;
import com.wits.platform.common.utils.PageUtil;
import com.wits.platform.common.utils.StringUtil;
import com.wits.platform.entity.MmrUserRole;
import com.wits.platform.entity.MmrUserRolePK;
import com.wits.platform.entity.User;
import com.wits.platform.service.UserService;
import com.wits.platform.web.controller.BaseController;
import com.wits.platform.web.mvc.AjaxResult;
import com.wits.platform.web.mvc.PageParam;
import com.wits.qso.entity.Btable;
import com.wits.qso.entity.Teacher;
import com.wits.qso.service.BtableDaoService;
import com.wits.qso.service.TeacherService;
import com.wits.qso.service.VmUserService;
import com.wits.qso.util.UserRoleType;

@Controller
@RequestMapping(value="qso/teacher")
public class TeacherController extends BaseController{
    
	private static final String ATTRIBUTE_TEACHER_BATCH_FILE = "teacherBatchFile";
	/** 注入TeacherService **/
	@Autowired
	private TeacherService teacherService;
	
	/**
	 * 注入userService
	 */
	@Autowired
	private UserService userService;
	@Autowired
	private PasswordService passwordService;
	@Autowired
	private BtableDaoService btableDaoService = null;
	
	@Autowired
	private VmUserService vmUserService = null;
	
	@RequestMapping(value="/toList")
	public String toList(){
		return "qso/teacher/list";
	}
	
	/**
	 * 加载老师信息列表
	 * @param model
	 * @param page
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/list")
	@ResponseBody
	public String list(Model model,@ModelAttribute("page") PageParam page,HttpServletRequest req){
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(req, "search_");
		Page<Teacher> listPage = teacherService.findPage(Teacher.class, searchParams, page);
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		return PageUtil.toAjaxPageResult(listPage.getTotalElements(), listPage.getContent());
	}
	
	/**
	 * 老师信息列表上按钮的触发事件处理
	 * @param model
	 * @param viewType
	 * @param terId
	 * @return
	 */
	@RequestMapping(value="/view/{viewType}")
	public String toView(Model model,@PathVariable String viewType,@RequestParam String terId){
		if(ViewType.Add.getView().equals(viewType)){
			model.addAttribute(WebConstants.COMMAND, new Teacher());
		}else{
			model.addAttribute(WebConstants.COMMAND, teacherService.getOne(terId));
		}
		model.addAttribute("viewType", viewType);
		return "qso/teacher/form";
	}
	
	/**
	 * 个人信息
	 * @param model
	 * @param terId
	 * @return
	 */
	@RequestMapping(value="/info")
	public String toInfo(Model model){
		model.addAttribute(WebConstants.COMMAND, teacherService.findByUserId(getCurrentUserId()));
		model.addAttribute("user", userService.getOne(getCurrentUserId()));
		model.addAttribute("vmuser", vmUserService.findByUserId(getCurrentUserId()));
		return "qso/teacher/info";
	}
	
	/**
	 * 修改密码
	 * @param model
	 * @param terId
	 * @return
	 */
	@RequestMapping(value="/changepwd")
	public Object chagePwd(Model model,@RequestParam String terUserId){
		model.addAttribute(WebConstants.COMMAND, teacherService.getUser(terUserId));
		return "qso/teacher/changepwd";
	}
	
	/**
	 * 新增、修改老师信息
	 * @param model
	 * @param command
	 * @param viewType
	 * @param result
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/save",method={RequestMethod.POST})
	@ResponseBody
	public Object save(Model model,
			@ModelAttribute("command") @Valid Teacher command,
			@RequestParam String viewType,
			BindingResult result,
			HttpServletRequest req){
		
		AjaxResult resultF=null;
		if(result.hasErrors()){
			model.addAttribute(WebConstants.COMMAND, command);
			return toView(model, viewType, command.getTerId());
		}
		
		User user=null;
		if(ViewType.Add.getView().equals(viewType)){
			command.setDateCre(new Date());
			command.setUserCre(getCurrentUserId());
			
			user=new User();
			user.setUserId(command.getTerUserId());
			user.setUserNameC(command.getTerName());
			user.setDateExpire(command.getDateExpire());
			user.setIsEnable("T"); //设置为true
			user.setUsertype(UserType.TEACHER.getValue());
			user.setUserCre(getCurrentUserId());
			user.setUserEmail(command.getTerMail());
	        String encrypted = passwordService.encryptPassword("123456");  
	        user.setUserPassword(encrypted);
			user.setDateCre(new Date());
			
			try {
				if(userService.isExist(user)){
					resultF= ajaxDoneError("登录账号已存在");
				}else{
					teacherService.save(command);
					userService.saveCascade(user);
					teacherService.insertUserRole(new MmrUserRole(new MmrUserRolePK(user.getUserId(), UserRoleType.TeacerRole.getValue())));
					resultF= ajaxDoneSuccess(this.getText("save.success"));
				}
			} catch (Exception e) {
				resultF= ajaxDoneError(this.getText("save.failed"), e);
			}
		}else{
			command.setDateUpd(new Date());
			command.setUserUpd(getCurrentUserId());
			user=userService.getOne(command.getTerUserId());
			user.setUserNameC(command.getTerName());
			user.setDateExpire(command.getDateExpire());
			try {
				teacherService.save(command);
				userService.save(user);
				resultF= ajaxDoneSuccess(this.getText("save.success"));
			} catch (Exception e) {
				resultF= ajaxDoneError(this.getText("save.failed"), e);
			}
		}
		return resultF;
	}
	
	/**
	 * 删除老师信息
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	@Transactional(readOnly=false,rollbackFor=DataAccessException.class)
	public Object delete(String ids){
		boolean hasSusscesed = false;
		boolean hasErrored = false;
		try {
			List<String> idList=Arrays.asList(StringUtil.split(ids, ","));
			
			for(String id : idList) {
				try {
					Teacher t=teacherService.getOne(id);
					teacherService.delete( id );
					teacherService.deleteUserRole(t.getTerUserId());
					userService.delete(t.getTerUserId());
					hasSusscesed = true;
				} catch (Exception e) {
					hasErrored = true;
					throw new DataAccessException("有些被引用的老师无法删除") {
						private static final long serialVersionUID = -5298757276222427020L;
					};
				}
			}
			
			if (hasSusscesed) {
				if (hasErrored) {
					return ajaxDoneError( "有些被引用的老师无法删除" );
				} else {
					return ajaxDoneSuccess(this.getText("delete.success"));
				}
			} else {
				return ajaxDoneError( "所选老师已经被引用，无法删除" );
			}
		} catch (Exception e) {
			return ajaxDoneError(this.getText("delete.failed"), e);
		}
	}
	
	/**
	 * 唯一键检查
	 * @param terId
	 * @param oldTerId
	 * @return
	 */
	@RequestMapping(value="/checkUniqueId")
	@ResponseBody
	public boolean checkUniqueId(@RequestParam("terId") String terId,@RequestParam("oldTerId") String oldTerId){
		if(terId.equals(oldTerId)){
			return true;
		}
		Teacher obj=teacherService.getOne(terId);
		return obj == null;
	}
	
	@RequestMapping(value = "/message")
	public String message(Model model) {
		Calendar calendar = Calendar.getInstance();
		
		Btable btable = btableDaoService.findByCurrentTime( calendar.getTime() );
		if (null == btable) {
			model.addAttribute( MESSAGES_KEY, "没有上课老师" );
		} else {
			model.addAttribute( WebConstants.COMMAND, btable.getTeaid() );
		}
		
		return "qso/teacher/message";
	}
	
	@RequestMapping(value = "/import")
	public String importData(Model model) {
		return "qso/teacher/import";
	}

	@RequestMapping(value = "/import/save", method = { RequestMethod.POST })
	@ResponseBody
	public Object importData(Model model, HttpSession session) {
		int result = 0;
		String uploadFile = (String) session.getAttribute( ATTRIBUTE_TEACHER_BATCH_FILE );
		try {
			if (null != uploadFile) {
				result = teacherService.batchTeacherData( new HSSFWorkbook( new FileInputStream( new File( session.getServletContext().getRealPath( "/" ) + uploadFile ) ) ), getCurrentUserId() );
				logger.info(" success : {}", result);
			}
			return ajaxDoneSuccess( this.getText( "save.success" ) );
		} catch (Throwable cause) {
			logger.info( cause.getMessage(), cause );
			return ajaxDoneError( this.getText( "save.failed" ) );
		}
	}

	@RequestMapping(value = "/import/upload")
	public void importDataUpload(@RequestParam(value = "attachment") MultipartFile multipartFile, HttpSession session) {
		String extension = FilenameUtils.getExtension( multipartFile.getOriginalFilename() );
		String uuid = UUID.randomUUID().toString().replace( "-", "" );
		String storagePath = WebConstants.UPLOAD_DIR + File.separator + "import" + File.separator + uuid;

		try {
			FileUtil.upload( multipartFile, session.getServletContext().getRealPath( "/" ) + storagePath, uuid + "." + extension );
			session.setAttribute( ATTRIBUTE_TEACHER_BATCH_FILE, storagePath + File.separator + uuid + "." + extension );
		} catch (Throwable cause) {
			logger.error( cause.getMessage(), cause );
		}
	}
}
